<template>
  <div class="search-song">
    <song-list :songList="currentSongList"></song-list>
  </div>
</template>

<script lang="ts">
import { onBeforeRouteLeave } from "vue-router";  // 从 vue-router 导入
import {defineComponent, ref, computed, watch, onMounted, getCurrentInstance} from "vue";
import {useStore} from "vuex";
import SongList from "@/components/SongList.vue";
import {HttpManager} from "@/api";

export default defineComponent({
  components: {
    SongList,
  },
  setup() {
    const {proxy} = getCurrentInstance();
    const store = useStore();

    const currentSongList = ref([]); // 存放的音乐
    const searchWord = computed(() => store.getters.searchWord);
    // 监听 searchWord 变化
    watch(searchWord, (value) => {
      searchSong(value);
    });

    // 搜索音乐
    async function searchSong(value) {
      // 如果搜索关键词为空，直接清空列表并返回
      if (!value || value.trim() === "") {
        currentSongList.value = [];
        return;
      }
      try {
        const result = (await HttpManager.getSongOfSingerName(value)) as ResponseBody;
        // 确保 result.data 存在且为数组
        if (result && Array.isArray(result.data) && result.data.length > 0) {
          currentSongList.value = result.data;
        } else {
          currentSongList.value = [];
          (proxy as any).$message({
            message: "暂时没有相关歌曲",
            type: "warning",
          });
        }
      } catch (error) {
        (proxy as any).$message({
          message: "搜索出错，请稍后再试",
          type: "error",
        });
      }
    }

    // 组件挂载时执行搜索
    onMounted(() => {
      searchSong(proxy.$route.query.keywords);
    });

    // 监听路由离开事件，清空搜索栏
    onBeforeRouteLeave((to, from, next) => {
      store.commit("setSearchWord", ""); // 清空搜索词
      next();
    });

    return {
      currentSongList,
    };
  },
});
</script>
